package counter;

import main.Main;

public class LocalMemWorkerThread extends Thread {

  private ICounter _counter;
  private CounterWithBarrier _syncedCounter;
  
  /**
   * C'tor
   * @param counter The shared synchronized counter obj.
   */
  public LocalMemWorkerThread(CounterWithBarrier syncedCounter) {
    _syncedCounter = syncedCounter;
    _counter = new Counter();
  }

  @Override
  public void run() {
    int cachedVal;
    int countTo = Main.getCountTo();
    for (int iterNum = 0; iterNum < countTo ; iterNum++) {
      cachedVal = _counter.getValue();
      _syncedCounter.await(); // all threads read the same value (each from his own counter)
      cachedVal++;
      _counter.setValue(cachedVal);
    }
    // For Debug
    // System.out.println("Thread " + getName() + " counter = " + _counter.getValue());
  }
}
